import {
  app,
  BrowserWindow,
  Menu,
  ipcMain,
  dialog,
  MenuItemConstructorOptions,
  globalShortcut,
  WebContentsView,
} from "electron";
// import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { mergePDFsToA4Grid } from './utils/index'
// const require = createRequire(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, "..");

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
export const MAIN_DIST = path.join(process.env.APP_ROOT, "dist-electron");
export const RENDERER_DIST = path.join(process.env.APP_ROOT, "dist");

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL
  ? path.join(process.env.APP_ROOT, "public")
  : RENDERER_DIST;

let win: BrowserWindow | null;
// 防止启动多个实例（多开窗口）
function CheckedInstance() {
  // 检查是否已存在实例
  const gotTheLock = app.requestSingleInstanceLock();
  if (!gotTheLock) {
    // 如果存在其他实例，直接退出当前进程
    app.quit();
  } else {
    // 首次启动或唯一实例
    app.on("second-instance", () => {
      // 当用户尝试再次启动应用时，激活已有窗口
      if (win) {
        if (win.isMinimized()) win.restore();
        win.show();
        win.focus();
      }
    });
  }
}
CheckedInstance();
// 注册快捷键
const registerShortcut = (mainWindow: BrowserWindow | WebContentsView) => {
  globalShortcut.register("Ctrl+Alt+F12", () => {
    if (mainWindow.webContents.isDevToolsOpened()) {
      mainWindow.webContents.closeDevTools();
    } else {
      mainWindow.webContents.openDevTools({ mode: "detach" });
    }
  });
};
const setMenu = () => {
  // 菜单栏模板
  const menuTemplate: Array<MenuItemConstructorOptions> = [];
  const menu = Menu.buildFromTemplate(menuTemplate);
  Menu.setApplicationMenu(menu);
};
function createWindow() {
  setMenu();
  win = new BrowserWindow({
    width: 1210,
    height: 769,
    icon: path.join(process.env.VITE_PUBLIC, "icons/icon.ico"),
    webPreferences: {
      preload: path.join(__dirname, "preload.mjs"),
    },
  });
  registerShortcut(win);
  // Test active push message to Renderer-process.
  win.webContents.on("did-finish-load", () => {
    win?.webContents.send("main-process-message", new Date().toLocaleString());
  });

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL);
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(path.join(RENDERER_DIST, "index.html"));
  }
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    win = null;
  }
});

app.on("activate", () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

app.whenReady().then(createWindow);

// 处理合并PDF请求
ipcMain.handle("merge-pdfs", async (_event, options: {filePaths: any[], columns: number, rows: number }) => {
  const { filePaths, columns, rows } = options;
  try {
    console.log("开始合并PDF...", filePaths);
    if(win == null) return;
    // 弹出“保存文件”对话框
    const { canceled, filePath } = await dialog.showSaveDialog(win, {
      title: "请选择保存合并后的pdf文件位置",
      defaultPath: "merged.pdf",
      filters: [{ name: "PDF 文件", extensions: ["pdf"] }]
    });

    if (canceled || !filePath) {
      return { success: false, message: "用户取消保存" };
    }

    await mergePDFsToA4Grid(filePaths, filePath, columns, rows);

    return { success: true, path: filePath };
  } catch (err: any) {
    return { success: false, message: err.message };
  }
})